import Cesium from '../Ces/Cesium'

class TimeSampleArray {
  property
  _times
  _urls
  _start
  _end
  _minStepSec
  _maxStepSec
  _fullSec
  constructor(urls, parseTime: any) {
    const property = new Cesium.SampledProperty(Number)
    property.backwardExtrapolationType = Cesium.ExtrapolationType.HOLD
    property.forwardExtrapolationType = Cesium.ExtrapolationType.HOLD
    const times = []
    for (let i = 0; i < urls.length; i++) {
      const julianDate = parseTime(urls[i])
      if (i === 0) {
        this._start = julianDate
      } else if (i === urls.length - 1) {
        this._end = julianDate
      }
      times.push(julianDate)
      property.addSample(julianDate, i)
      if (i > 0) {
        const sec = Cesium.JulianDate.secondsDifference(
          times[i],
          times[i - 1],
        )
        if (!this._minStepSec || this._minStepSec > sec) this._minStepSec = sec
        if (!this._maxStepSec || this._maxStepSec < sec) this._maxStepSec = sec
        if (i === urls.length - 1) {

          this._fullSec = Cesium.JulianDate.secondsDifference(julianDate, times[0])
        }
      }
    }
    this.property = property
    this._urls = urls
    this._times = times
  }

  getIndex(time) {
    const i = this.sampleProperty.getValue(time)
    return Cesium.defined(i) ? Math.floor(i) : 0
  }

  getNextIndex(time) {
    return Math.ceil(this.sampleProperty.getValue(time))
  }

  getUrlByTime(time) {
    const i = this.getIndex(time)
    return this._urls[i]
  }

  getUrl(index) {
    if (index instanceof Cesium.JulianDate) {
      const i = this.getIndex(index)
      return this._urls[i]
    }
    return this._urls[index]
  }

  getTime(index) {
    return this._times[index]
  }
  get minStepSec() {
    return this._minStepSec
  }
  get maxStepSec() {
    return this._maxStepSec
  }
  get start() {
    return this._start
  }
  get end() {
    return this._end
  }
  get sampleProperty() {
    return this.property
  }
  get urls() {
    return this._urls
  }
  get times() {
    return this._times
  }
  get length() {
    return this._urls.length
  }
  get fullSec() {
    return this._fullSec
  }
}

export default TimeSampleArray
